﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.Base;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;

namespace Corina.Lantern.Hub.Viewmodels
{
    public class ManualEntryViewmodel : ViewmodelBase
    {
        public ManualEntryViewmodel() {
            DatasClient.GetSpecimenKindItemsCompleted += GetSpecimenKindItemsCompleted;
            ThirdMeasureClient.SubmitMeasureCompleted += SubmitMeasureCompleted;
            ThirdMeasureClient.GetAllMeasureItemsCompleted += GetAllMeasureItemsCompleted;
            DatasClient.GetSpecimenKindItemsAsync(Account, Password);

            if (DataContext.IsValid)
            {
                LoadData();
            }
        }

        private void GetAllMeasureItemsCompleted(object sender, DataService.ExecuteCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects
                                 select new
                                 {
                                     ItemIndex = t["ROW_NUMBER"],
                                     Id = t["Id"],
                                     Applicant = (string)t["Applicant"],
                                     ApplyUnit = (string)t["ApplyUnit"],
                                     ApplyDate = t["ApplyDate"],
                                     MeasureObject = t["MeasureObject"],
                                     Density = (double)t["Density"],
                                     DensityUnit = t["DensityUnit"],
                                     Temperature = (double)t["Temperature"],
                                     Humidity = (double)t["Humidity"],
                                     Tester = (string)t["Tester"],
                                     Specimen = t["Specimen"],
                                     SpecimenKind = t["SpecimenKind"],
                                     MeasureTime = Convert.ToDateTime(t["MeasureTime"]),
                                     UserName = t["UserName"],
                                     Guobiao = t["Guobiao"],
                                     DocumentName = t["DocumentName"],
                                     PreviewImage = t["PreviewImage"]
                                 });
                    ItemsCollection = new ObservableCollection<object>(items);
                    ItemsCount = e.Result.TotalCount;
                    
                }
            }

            IsBusy = false;
        }

        private void SubmitMeasureCompleted(object sender, DataService.ExecuteCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                SelectedSpecimen = null;
                UpdateEntity = new ThirdPartyMeasureInfo();
                Operation = EntityOperation.None;
                RaisePropertyChanged(() => SubmitCommand);

                LoadData();
            }
        }

        private void GetSpecimenKindItemsCompleted(object sender, DataService.ExecuteCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                SpecimenKindCollection = new ObservableCollection<SpecimenKindInfo>(e.Result.Entities.OfType<SpecimenKindInfo>());
            }
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            string conditions = JsonHelper.Stringify(new List<QueryCondition>());
            ThirdMeasureClient.GetAllMeasureItemsAsync(Account, Password, 0, "", 0, "", "", conditions, Index, 20);
        }


        #region Collection
        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private ObservableCollection<SpecimenKindInfo> _specimenKindCollection;
        public ObservableCollection<SpecimenKindInfo> SpecimenKindCollection
        {
            get { return _specimenKindCollection; }
            set {
                _specimenKindCollection = value;
                RaisePropertyChanged(() => SpecimenKindCollection);
            }
        }

        private SpecimenKindInfo _selectedSpecimen;
        public SpecimenKindInfo SelectedSpecimen
        {
            get { return _selectedSpecimen; }
            set {
                _selectedSpecimen = value;
                RaisePropertyChanged(() => SelectedSpecimen);
                UpdateEntity.SpecimenKindId = SelectedSpecimen == null ? 0 : SelectedSpecimen.Id;
                RaisePropertyChanged(() => SubmitCommand);
            }
        }

        #endregion

        public IEnumerable<string> DensityUnit
        {
            get
            {
                yield return "ppm";
                yield return "ppp";
                yield return "ppt";
            }
        }

        #region Update
        public ICommand InsertCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Operation = EntityOperation.Insert;
                    }
                };
            }
        }

        private bool _agreePolicy = false;
        public bool AgreePolicy
        {
            get { return _agreePolicy; }
            set
            {
                _agreePolicy = value;
                RaisePropertyChanged(() => AgreePolicy);
                RaisePropertyChanged(() => SubmitCommand);
            }
        }

        private ThirdPartyMeasureInfo _updateEntity = new ThirdPartyMeasureInfo();
        public ThirdPartyMeasureInfo UpdateEntity
        {
            get {
                return _updateEntity;
            }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
                RaisePropertyChanged(() => SubmitCommand);
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate
                    {
                        return AgreePolicy && UpdateEntity.ApplyDate != null && UpdateEntity.MeasureTime != null && !string.IsNullOrEmpty(UpdateEntity.MeasureObject) && !string.IsNullOrEmpty(UpdateEntity.Specimen) && UpdateEntity.SpecimenKindId > 0;
                    },
                    ExecuteCallback = delegate
                    {
                        UpdateEntity.UserId = DataContext.CurrentAccount.Id;
                        string jsonString = JsonHelper.Stringify(UpdateEntity);
                        ThirdMeasureClient.SubmitMeasureAsync(Account, Password, jsonString);
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        SelectedSpecimen = null;
                        UpdateEntity = new ThirdPartyMeasureInfo();

                        Operation = EntityOperation.None;
                    }
                };
            }
        }
        #endregion
    }
}
